import { Subject } from '@entity/Subject'
import { EventEmitter } from '@helpers/EventEmitter'
import { CheckResultInter } from '@routes'
import { getRepository } from 'typeorm'
import { MysqlService } from './MysqlService'

export class SubjectService extends EventEmitter {
  public mysqlService!: MysqlService
  constructor(mysqlService: MysqlService) {
    super()
    this.mysqlService = mysqlService
  }

  public async createSubject(subjectData: Subject): Promise<CheckResultInter & { id?: number }> {
    const { name, schooltime, studentCount, yearPrice, halfYearPrice, cover, banners } = subjectData
    const subject = new Subject()
    subject.name = name
    subject.banners = banners || '[]'
    subject.schooltime = schooltime
    subject.studentCount = studentCount
    subject.yearPrice = yearPrice
    subject.halfYearPrice = halfYearPrice
    subject.cover = cover
    try {
      const { id } = await getRepository(Subject).save(subject)
      return { msg: '', code: 0, id }
    } catch (error) {
      console.error(error)
      return { code: 4005, msg: 'insert error [ createSubject ]' }
    }
  }

  public async getSubjectList(offset: number, count: number, ): Promise<CheckResultInter & { list: Subject[] }> {
    try {
      // take => limit; skip => offset
      const list = await getRepository(Subject).find({
        take: count,
        skip: offset
      })
      return { code: 0, msg: '', list }
    } catch (error) {
      console.error(error)
      return { code: 4005, msg: 'query error [ getSubjectList ]', list: [] }
    }
  }

  public async getSubjectById(id: number): Promise<CheckResultInter & { subject?: Subject }> {
    try {
      // take => limit; skip => offset
      const subject = await getRepository(Subject).findOne({ id })
      if (!subject) {
        return { code: 4004, msg: '系统档案中没有该课程资料' }
      }
      return { code: 0, msg: '', subject }
    } catch (error) {
      console.error(error)
      return { code: 4005, msg: 'query error [ getSubjectById ]' }
    }
  }

  public async updateSubjectInfo(id: number, data: Partial<Subject>): Promise<CheckResultInter> {
    try {
      await getRepository(Subject).update({ id }, data)
      return { code: 0, msg: '' }
    } catch (error) {
      console.error(error)
      return { code: 4006, msg: 'update error [ updateStudentInfo ]' }
    }
  }

}
